<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <p>分数: <span id="score">0</span></p>
    <div>
        <button id="restartButton">重新开始</button>
        <button id="showHistoryButton">显示历史记录</button>
        <button id="clearHistoryButton">清除历史记录</button>
        <button id="pauseButton">暂停</button> <!-- 添加暂停按钮 -->
    </div>
    <div id="historyRecords"></div>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const blockSize = 20;
        const widthInBlocks = canvas.width / blockSize;
        const heightInBlocks = canvas.height / blockSize;
        const scoreElement = document.getElementById('score');
        const restartButton = document.getElementById('restartButton');
        const showHistoryButton = document.getElementById('showHistoryButton');
        const clearHistoryButton = document.getElementById('clearHistoryButton');
        const pauseButton = document.getElementById('pauseButton'); // 获取暂停按钮
        const historyRecords = document.getElementById('historyRecords');

        let snake;
        let apple;
        let bomb;
        let score = 0;
        let direction;
        let gameInterval;
        let history = [];
        let isPaused = false; // 跟踪游戏是否暂停

        // 初始化蛇
        function initSnake() {
            snake = [
                { x: 5, y: 5 },
                { x: 4, y: 5 },
                { x: 3, y: 5 }
            ];
        }

        // 初始化苹果
        function initApple() {
            apple = {
                x: Math.floor(Math.random() * widthInBlocks),
                y: Math.floor(Math.random() * heightInBlocks)
            };
        }

        // 初始化炸弹
        function initBomb() {
            bomb = {
                x: Math.floor(Math.random() * widthInBlocks),
                y: Math.floor(Math.random() * heightInBlocks)
            };
            // 确保炸弹不与苹果和蛇重叠
            while (isCollision(bomb, apple) || snake.some(segment => isCollision(segment, bomb))) {
                bomb = {
                    x: Math.floor(Math.random() * widthInBlocks),
                    y: Math.floor(Math.random() * heightInBlocks)
                };
            }
        }

        // 检查碰撞
        function isCollision(a, b) {
            return a.x === b.x && a.y === b.y;
        }

        // 绘制方块
        function drawBlock(ctx, position) {
            const x = position.x * blockSize;
            const y = position.y * blockSize;
            ctx.fillRect(x, y, blockSize, blockSize);
        }

        // 绘制蛇
        function drawSnake() {
            ctx.fillStyle = 'green';
            snake.forEach(drawBlock.bind(null, ctx));
        }

        // 绘制苹果
        function drawApple() {
            ctx.fillStyle = 'red';
            drawBlock(ctx, apple);
        }

        // 绘制炸弹
        function drawBomb() {
            ctx.fillStyle = 'black';
            drawBlock(ctx, bomb);
        }

        // 更新蛇的位置
        function moveSnake() {
            const head = { ...snake[0] };
            switch (direction) {
                case 'right':
                    head.x++;
                    break;
                case 'left':
                    head.x--;
                    break;
                case 'up':
                    head.y--;
                    break;
                case 'down':
                    head.y++;
                    break;
            }
            snake.unshift(head);

            if (isCollision(head, apple)) {
                score++;
                scoreElement.textContent = score;
                initApple();
                initBomb();
            } else if (isCollision(head, bomb)) {
                score = Math.max(0, score - 1);
                scoreElement.textContent = score;
                initBomb();
            } else {
                snake.pop();
            }
        }

        // 检查游戏是否结束
        function checkGameOver() {
            const head = snake[0];
            if (head.x < 0 || head.x >= widthInBlocks || head.y < 0 || head.y >= heightInBlocks) {
                return true;
            }
            for (let i = 1; i < snake.length; i++) {
                if (isCollision(head, snake[i])) {
                    return true;
                }
            }
            return false;
        }

        // 绘制游戏
        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            drawSnake();
            drawApple();
            drawBomb();
        }

        // 游戏循环
        function gameLoop() {
            if (!isPaused) { // 如果游戏没有暂停
                moveSnake();
                if (checkGameOver()) {
                    clearInterval(gameInterval);
                    const endTime = new Date().toLocaleString();
                    history.push({ score, endTime });
                    localStorage.setItem('gameHistory', JSON.stringify(history));
                    alert(`游戏结束！你的分数是: ${score}`);
                }
                draw();
            }
        }

        // 处理键盘事件
        document.addEventListener('keydown', function (event) {
            switch (event.key) {
                case 'ArrowRight':
                    if (direction !== 'left') direction = 'right';
                    break;
                case 'ArrowLeft':
                    if (direction !== 'right') direction = 'left';
                    break;
                case 'ArrowUp':
                    if (direction !== 'down') direction = 'up';
                    break;
                case 'ArrowDown':
                    if (direction !== 'up') direction = 'down';
                    break;
            }
        });

        // 重新开始游戏
        function restartGame() {
            clearInterval(gameInterval);
            score = 0;
            scoreElement.textContent = score;
            initSnake();
            initApple();
            initBomb();
            direction = 'right';
            isPaused = false; // 重置暂停状态
            gameInterval = setInterval(gameLoop, 200);
        }

        // 显示历史记录
        function showHistory() {
            historyRecords.innerHTML = '';
            history.forEach((record, index) => {
                const p = document.createElement('p');
                p.textContent = `第 ${index + 1} 局 - 分数: ${record.score}, 结束时间: ${record.endTime}`;
                historyRecords.appendChild(p);
            });
        }

        // 清除历史记录
        function clearHistory() {
            history = [];
            localStorage.removeItem('gameHistory');
            historyRecords.innerHTML = '';
        }

        // 游戏暂停
        function pauseGame() {
            isPaused = !isPaused; // 切换暂停状态
            if (isPaused) {
                pauseButton.textContent = '继续';
            } else {
                pauseButton.textContent = '暂停';
            }
        }

        // 初始化游戏
        function initGame() {
            const storedHistory = localStorage.getItem('gameHistory');
            if (storedHistory) {
                history = JSON.parse(storedHistory);
            }
            restartGame();
            restartButton.addEventListener('click', restartGame);
            showHistoryButton.addEventListener('click', showHistory);
            clearHistoryButton.addEventListener('click', clearHistory);
            pauseButton.addEventListener('click', pauseGame); // 添加暂停按钮的点击事件
        }

        initGame();
    </script>
</body>

</html>
